import { deleteGeneratorUsingPost, listGeneratorByPageUsingPost } from '@/services/backend/generatorController';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { Button, message, Select, Space, Tag, Typography, Modal } from 'antd';
import React, { useRef, useState } from 'react';
import {useNavigate} from "react-router-dom";

/**
 * 代码生成器管理页面
 * @constructor
 */
const GeneratorAdminPage: React.FC = () => {
  const [jsonModalVisible, setJsonModalVisible] = useState<boolean>(false);
  const [jsonData, setJsonData] = useState<string>('');
  const [modalTitle, setModalTitle] = useState<string>('');
  const actionRef = useRef<ActionType>();
  // 用来跳转页面
  const navigate = useNavigate();


  const showJsonModal = (title: string, value?: string) => {
    setModalTitle(title);
    setJsonData(value || '');
    setJsonModalVisible(true);
  };


  /**
   * 删除节点
   * @param row
   */
  const handleDelete = async (row: API.Generator) => {
    const hide = message.loading('正在删除');
    if (!row) return true;
    try {
      await deleteGeneratorUsingPost({
        id: row.id as any,
      });
      hide();
      message.success('删除成功');
      actionRef?.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };


  /**
   * 表格列配置
   */
  const columns: ProColumns<API.Generator>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '名称',
      dataIndex: 'name',
      valueType: 'text',
    },
    {
      title: '描述',
      dataIndex: 'description',
      valueType: 'textarea',
    },
    {
      title: '基础包名',
      dataIndex: 'basePackage',
      valueType: 'text',
    },
    {
      title: '版本',
      dataIndex: 'version',
      valueType: 'text',
    },
    {
      title: '作者',
      dataIndex: 'author',
      valueType: 'text',
    },
    {
      title: '标签',
      dataIndex: 'tags',
      valueType: 'text',
      renderFormItem: (schema) => {
        const { fieldProps } = schema;
        // @ts-ignore
        return <Select {...fieldProps} mode="tags" />;
      },
      render(_, record) {
        if (!record.tags) {
          return <></>;
        }
        try {
          return JSON.parse(record.tags).map((tag: string) => <Tag key={tag}>{tag}</Tag>);
        } catch (e) {
          return <Tag color="error">解析错误</Tag>;
        }
      },
    },
    {
      title: '图片',
      dataIndex: 'picture',
      valueType: 'image',
      fieldProps: {
        width: 64,
      },
      hideInSearch: true,
    },
    {
      title: '文件配置',
      dataIndex: 'fileConfig',
      render: (_, record) => [
        <Button
          type="link"
          key="config"
          onClick={() => showJsonModal('文件配置', record.fileConfig)}
        >
          点击查看
        </Button>
      ],
      hideInSearch: true,
    },
    {
      title: '模型配置',
      dataIndex: 'modelConfig',
      render: (_, record) => [
        <Button
          type="link"
          key="config"
          onClick={() => showJsonModal('模型配置', record.modelConfig)}
        >
          点击查看
        </Button>
      ],
      hideInSearch: true,
    },
    {
      title: '产物包路径',
      dataIndex: 'distPath',
      valueType: 'text',
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: {
          text: '默认',
        }
      },
    },
    {
      title: '创建用户',
      dataIndex: 'userId',
      valueType: 'text',
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size="middle">
          <Typography.Link
            onClick={() => {
              navigate(`/generator/update?id=${record.id}`);
            }}
          >
            修改
          </Typography.Link>
          <Typography.Link type="danger" onClick={() => handleDelete(record)}>
            删除
          </Typography.Link>
        </Space>
      ),
    },
  ];

  return (
    <div className={"generator-admin-page"}>
      <Typography.Title level={4} style={{ marginBottom: 16 }}>生成器管理</Typography.Title>
      <ProTable<API.Generator>
        headerTitle={'生成器列表'}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
          filterType: 'light',
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              navigate(`/generator/add`);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params, sort, filter) => {
          const sortField = Object.keys(sort)?.[0];
          const sortOrder = sort?.[sortField] ?? undefined;

          const { data, code } = await listGeneratorByPageUsingPost({
            ...params,
            sortField,
            sortOrder,
            ...filter,
          } as API.GeneratorQueryRequest);

          return {
            success: code === 0,
            data: data?.records || [],
            total: Number(data?.total) || 0,
          };
        }}
        columns={columns}
      />

      {/* JSON展示模态框 */}
      <Modal
        title={modalTitle}
        width={800}
        open={jsonModalVisible}
        onCancel={() => setJsonModalVisible(false)}
        footer={null}
        destroyOnClose
      >
        <div style={{ maxHeight: '60vh', overflow: 'auto' }}>
          <pre style={{
            fontSize: 14,
            lineHeight: 1.5,
            padding: 12,
            borderRadius: 4,
            backgroundColor: '#f6f8fa',
            whiteSpace: 'pre-wrap',
            wordWrap: 'break-word'
          }}>
            {jsonData ? JSON.stringify(JSON.parse(jsonData), null, 2) : '空数据'}
          </pre>
        </div>
      </Modal>
    </div>
  );
};

export default GeneratorAdminPage;
